package com.egghiro.framework.j2se.game.core.key;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class SKeyHandler implements KeyListener {
    private SKeyState keyState;
    private SKeyCodeMapper keyCodeMapper;
    private SKeyQueue keyQueue;

    // public SKeyHandler(){
    // this(new SKeyState());
    // }

    public SKeyHandler(SKeyState keyState) {
        this.keyState = keyState;
        this.keyCodeMapper = new SKeyCodeMapper();// TODO
        this.keyQueue = new SKeyQueue(); // TODO 使わない時もったいない
    }

    private boolean keyPressed(SGameKeyCode gameKeyCode) {
        synchronized (this.keyState) {
            // TODO テスト用
            switch (gameKeyCode) {
            case GAME_UP_CODE:
                return this.keyState.pressKeyUp();
                // break;
            case GAME_DOWN_CODE:
                return this.keyState.pressKeyDown();
                // break;
            case GAME_LEFT_CODE:
                return this.keyState.pressKeyLeft();
                // break;
            case GAME_RIGHT_CODE:
                return this.keyState.pressKeyRight();
                // break;
            default:
                return false;
                // break;
            }
        }
    }

    private void keyReleased(SGameKeyCode gameKeyCode) {
        synchronized (this.keyState) {
            // TODO テスト用
            switch (gameKeyCode) {
            case GAME_UP_CODE:
                this.keyState.releaseKeyUp();
                break;
            case GAME_DOWN_CODE:
                this.keyState.releaseKeyDown();
                break;
            case GAME_LEFT_CODE:
                this.keyState.releaseKeyLeft();
                break;
            case GAME_RIGHT_CODE:
                this.keyState.releaseKeyRight();
                break;
            default:
                break;
            }
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        SGameKeyCode gameKeyCode = this.keyCodeMapper.getGameKeyCode(e.getKeyCode());
        if (this.keyPressed(gameKeyCode)) {
            this.keyQueue.add(gameKeyCode);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        this.keyReleased(this.keyCodeMapper.getGameKeyCode(e.getKeyCode()));
    }

    @Override
    public void keyTyped(KeyEvent e) {
        //DO NOTHING
    }
}
